package com.zc.config;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @description:
 * @author: cong
 * @create: 2024/10/9
 */
@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    /**
     * 注册Hystrix监控Servlet
     *
     * 通过此方法，我们注册了一个Servlet，用于流式传输Hystrix度量数据
     * 这对于监控和可视化Hystrix在分布式系统中的表现至关重要
     *
     * @return ServletRegistrationBean 返回一个Servlet注册对象，用于注册HystrixMetricsStreamServlet
     */
    @Bean
    public ServletRegistrationBean getServlet() {
        // 创建HystrixMetricsStreamServlet实例，该Servlet用于流式传输Hystrix度量数据
        HystrixMetricsStreamServlet hystrixMetricsStreamServlet = new HystrixMetricsStreamServlet();
        // 初始化Servlet注册对象
        ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<>(hystrixMetricsStreamServlet);
        // 设置Servlet在应用启动时加载，优先级为1
        registrationBean.setLoadOnStartup(1);
        // 映射Servlet到/hystrix.stream路径，使得该路径可以访问到Servlet
        registrationBean.addUrlMappings("/hystrix.stream");
        // 设置Servlet的名称
        registrationBean.setName("HystrixMetricsStreamServlet");
        // 返回Servlet注册对象
        return registrationBean;
    }
}
